package com.qk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.constant.BusinessChannelConstants;
import com.qk.constant.BusinessStatusConstants;
import com.qk.domain.business.BusinessDO;
import com.qk.domain.business.BusinessTrackRecordDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessFollowUpdateDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.mapper.BusinessTrackRecordMapper;
import com.qk.mapper.CustomerMapper;
import com.qk.service.BusinessService;
import com.qk.mapper.BusinessMapper;
import com.qk.util.CurrentUserContextHolders;
import com.qk.vo.business.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author SweetHurt
 * @description 针对表【business(商机表)】的数据库操作Service实现
 * @createDate 2025-10-15 15:34:09
 */
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
        implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public PageResult<BusinessDO> getBusinessByPage(BusinessDTO businessDTO) {
        Page<BusinessDO> listPage = businessMapper.selectBusinessByPage(
                new Page<>(businessDTO.getPage(), businessDTO.getPageSize()),
                businessDTO
        );
        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(listPage.getTotal()).intValue())
                .rows(listPage.getRecords())
                .build();
    }

    @Override
    public boolean addBusiness(Business business) {
        if(!ObjectUtil.isAllNotEmpty(business, business.getPhone(), business.getName())) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        business.setUpdateTime(LocalDateTime.now());
        business.setCreateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setChannel(BusinessChannelConstants.ONLINE_ACTIVITY);
        return save(business);
    }

    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        Business business = getById(id);
        if (ObjectUtil.isEmpty(business)) {
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        List<BusinessTrackRecordDO> recordDOList = businessTrackRecordMapper.selectList(Wrappers.<BusinessTrackRecord>lambdaQuery()
                .eq(BusinessTrackRecord::getBusinessId, business.getId())
        ).stream().map(x -> {
            BusinessTrackRecordDO recordDO = BeanUtil.copyProperties(x, BusinessTrackRecordDO.class);
            recordDO.setAssignName(CurrentUserContextHolders.getName());
            return recordDO;
        }).collect(Collectors.toList());
        BusinessVO vo = BeanUtil.copyProperties(business, BusinessVO.class);
        vo.setTrackRecords(recordDOList);
        return vo;
    }

    @Override
    public boolean assignBusiness(Integer businessId, Integer userId) {
        if (!ObjectUtil.isAllNotEmpty(businessId, userId)) {
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        return update(Wrappers.<Business>lambdaUpdate()
                .eq(Business::getId, businessId)
                .set(Business::getUserId, userId)
                .set(Business::getStatus, BusinessStatusConstants.WAIT_FOLLOW_UP)
                .set(Business::getUpdateTime, LocalDateTime.now()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(BusinessFollowUpdateDTO dto) {
        if (!ObjectUtil.isAllNotEmpty(dto, dto.getId(), dto.getRecord(), dto.getNextTime(), dto.getTrackStatus(), dto.getKeyItems())) {
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class, "phone", "status", "channel", "clueId", "userId", "createTime", "updateTime");
        Business byId = getById(dto.getId());
        if (NumberUtil.equals(byId.getStatus(), BusinessStatusConstants.WAIT_FOLLOW_UP)) {
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        business.setUserId(CurrentUserContextHolders.getId());
        business.setUpdateTime(LocalDateTime.now());
        updateById(business);
        BusinessTrackRecord record = BusinessTrackRecord.builder()
                .businessId(dto.getId())
                .userId(CurrentUserContextHolders.getId())
                .trackStatus(dto.getTrackStatus())
                .nextTime(dto.getNextTime())
                .record(dto.getRecord())
                .createTime(LocalDateTime.now())
                .build();
        if (ObjectUtil.isNotEmpty(dto.getKeyItems())) {
            record.setKeyItems(StrUtil.join(", ", dto.getKeyItems()));
        }
        businessTrackRecordMapper.insert(record);
        return true;
    }

    @Override
    public boolean backBusiness(Integer id) {
        return update(Wrappers.<Business>lambdaUpdate()
                .eq(Business::getId, id)
                .set(Business::getStatus, BusinessStatusConstants.RECOVERY)
                .set(Business::getUpdateTime, LocalDateTime.now())
        );
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean toCustomer(Integer id) {
        Business business = getById(id);
        if (ObjectUtil.isEmpty(business)) {
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        Customer customer = BeanUtil.copyProperties(business, Customer.class, "id");
        customer.setBusinessId(business.getId());
        customer.setUpdateTime(LocalDateTime.now());
        customer.setCreateTime(LocalDateTime.now());
        customerMapper.insert(customer);
        return update(Wrappers.<Business>lambdaUpdate()
                .eq(Business::getId, business.getId())
                .set(Business::getStatus, BusinessStatusConstants.CONVERT_TO_CUSTOMER)
                .set(Business::getUpdateTime, LocalDateTime.now())
        );
    }
}




